package com.yhh.college_information_platform.controller;

import com.yhh.college_information_platform.annotation.PublicAccess;
import com.yhh.college_information_platform.common.Result;
import com.yhh.college_information_platform.service.FilePreviewService;
import com.yhh.college_information_platform.vo.FileContentVO;
import com.yhh.college_information_platform.vo.FilePreviewVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 文件预览Controller（所有接口游客可访问）
 *
 * @author yhh
 * @date 2025-10-29
 */
@Slf4j
@RestController
@RequestMapping("/resource")
@PublicAccess  // 游客可以预览文件
public class FilePreviewController {

    @Autowired
    private FilePreviewService filePreviewService;

    /**
     * 获取文件预览信息
     * 返回预签名URL和预览类型
     *
     * @param id 资料ID
     * @param request 请求对象
     * @return 预览信息
     */
    @GetMapping("/{id}/preview/url")
    public Result<FilePreviewVO> getPreviewUrl(@PathVariable Long id, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        FilePreviewVO previewVO = filePreviewService.getPreviewInfo(id, userId);
        return Result.success(previewVO);
    }

    /**
     * 获取文本文件内容
     * 用于TXT、MD等文本文件的预览
     *
     * @param id 资料ID
     * @param request 请求对象
     * @return 文件内容
     */
    @GetMapping("/{id}/preview/content")
    public Result<FileContentVO> getTextContent(@PathVariable Long id, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        FileContentVO contentVO = filePreviewService.getTextFileContent(id, userId);
        return Result.success(contentVO);
    }

    /**
     * 检查文件是否支持预览
     *
     * @param id 资料ID
     * @param request 请求对象
     * @return 支持信息
     */
    @GetMapping("/{id}/preview/support")
    public Result<Boolean> checkPreviewSupport(@PathVariable Long id, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        FilePreviewVO previewVO = filePreviewService.getPreviewInfo(id, userId);
        return Result.success(previewVO.getSupported());
    }
}

